/**
 * 
 */
package cn.edu.nju.ws.sview.wyge.relations.adataset.relations;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * @author Weiyi Ge (geweiyi@gmail.com) 2012-8-15
 * 
 */
public class Pattern {
	private ArrayList<TriplePattern> triples = new ArrayList<TriplePattern>();
	
	public Pattern clone(){
		Pattern p = new Pattern();
		for(TriplePattern t : this.triples){
			p.addTriple(t);
		}
		return p;
	}
	public String toString() {
		String pat = "";
		for (TriplePattern t : triples) {
			pat += t.toString() + "\r\n";
		}
		return pat;
	}

	public void bindVariable(String v, String value) {
		for (TriplePattern t : triples) {
			t.bindVariable(v, value);
		}
	}

	public List<String> getVariables() {
		HashSet<String> variables = new HashSet<String>();
		for (TriplePattern t : triples) {
			String s = t.getSubject();
			String o = t.getObject();
			if (s.startsWith("v")) {
				variables.add(s);
			}
			if (o.startsWith("v")) {
				variables.add(o);
			}
		}
		List<String> keyList = new ArrayList<String>(variables);
		Collections.sort(keyList, new VariableComparator());
		return keyList;
	}

	public ArrayList<TriplePattern> getTriples() {
		return triples;
	}
	
	public void addTriple(String s, int p, String o){
		TriplePattern t = new TriplePattern(s, p, o);
		triples.add(t);
	}
	
	public void addTriple(TriplePattern t) {
		triples.add(t);
	}

	public boolean canDel(String s, int p, String o) {
		HashSet<String> v = new HashSet<String>();
		UnionFind uf = new UnionFind();
		if (triples.size() <= 1)
			return false;
		for (TriplePattern t : triples) {
			String s1 = t.getSubject();
			int p1 = t.getProperty();
			String o1 = t.getObject();
			if (!s1.equals(s) || p1 != p || !o1.equals(o)) {
				uf.union(s1, o1);
				v.add(s1);
				v.add(o1);
			}
		}
		HashSet<String> tmp = new HashSet<String>();
		for (String vv : v) {
			tmp.add(uf.find(vv));
		}
		if (tmp.size() > 1) {
			return false;
		}
		return true;
	}

	public void delTriple(String s, int p, String o) {
		for (TriplePattern t : triples) {
			String s1 = t.getSubject();
			int p1 = t.getProperty();
			String o1 = t.getObject();
			if (s1.equals(s) && p1 == p && o1.equals(o)) {
				triples.remove(t);
				break;
			}
		}
	}
}
